package com.qf.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.api.CacheFeign;
import com.qf.constant.CacheConstants;
import com.qf.model.StandardSubmit;
import com.qf.service.FilterChainManager;
import com.qf.service.FilterChainService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * @author WuZiYu
 * @date 2022-6-7 下午 6:57
 */
@Service
@Slf4j
public class FilterChainManagerImpl implements FilterChainManager {

    /**
     * 在springIOC容器中  六个实现类共用同一个接口  注入一个Map
     */
    @Autowired
    private Map<String, FilterChainService> filterChainServiceMap;
    @Autowired
    private CacheFeign cacheFeign;
    @Autowired
    private ObjectMapper objectMapper;
    /**
     * 责任链管理者   会执行大量的策略
     * @param standardSubmit
     */
    @Override
    public void executeFilter(StandardSubmit standardSubmit) throws Exception{

        //六个策略

        //号段补全策略
        //FilterChainService PhaseFilterChainServiceImpl = filterChainServiceMap.get("phase");

        //调用cache模块获取redis中过滤器的执行顺序
        Integer clientID = standardSubmit.getClientID();
        //"phase,black,limitFiveMinutes,dirtyWords,fee,router"
        String filters = cacheFeign.hget(
                CacheConstants.CACHE_PREFIX_CLIENT + clientID, "filters");
        //1获取执行的过滤器实现类对象
//        String filters = (String) cacheFeign.hget(CacheConstants.CACHE_PREFIX_CLIENT + clientID, "filters");
        if (StringUtils.isEmpty(filters)){
            log.info("[策略模块 - 策略管理员] 无策略可以执行, submit = {}", objectMapper.writeValueAsString(standardSubmit));
            return;
        }
        //2根据都好分割  获取过滤器执行顺序数组
        String[] filterArray = filters.split(",");
        //3遍历过滤器执行顺序数组
        for (String filter : filterArray) {
//        4. 获取执行的过滤器实现类对象, FilterChainService chain = filterMap.get("phase")
            FilterChainService filterChainService=filterChainServiceMap.get(filter);
            //执行策略
//        5. 执行具体策略业务方法, chain.strategy(StandardSubmit submit);
            boolean flag = filterChainService.strategy(standardSubmit);
            //        6. 判断执行结果, 如果返回为false停止执行, 返回为true继续执行
            if (!flag){
                //false停止执行
                //记录日志
                log.error("[策略模块 - 策略管理员]"+filter+" 所有策略执行完毕, submit = {}",
                        objectMapper.writeValueAsString(standardSubmit));
                return;
            }
        }
    }
}
